const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../services/user.js');
var WxParse = require('../../lib/wxParse/wxParse.js');


//获取应用实例
const app = getApp()

Page({
    data: {
        navList: [],
        categoryList: [],
        currentCategory: {},
        goodsCount: 0,
        nowIndex: 0,
        nowId: 0,
        list: [],
        allPage: 1,
        allCount: 0,
        size: 10,
        hasInfo: 0,
        showNoMore: 0,
        loading:0,
        index_banner_img:0,
        toView: 'green',
        floorGoods: [],
        showChannel: 0,
        showBanner: 0,
        showBannerImg: 0,
        banner: [],
        index_banner_img: 0,
        userInfo: {},
        imgurl: '',
        sysHeight: 0,
        loading: 0,
        autoplay:true,
        showContact:1,
        goods: {},
        id: 0,
        gallery: [],
        galleryImages:[],
        specificationList: [],
        productList: [],
        cartGoodsCount: 0,
        checkedSpecPrice: 0,
        number: 1,
        checkedSpecText: '',
        tmpSpecText: '请选择规格和数量',
        openAttr: false,
        soldout: false,
        disabled: '',
        alone_text: '单独购买',
        userId: 0,
        priceChecked: false,
        goodsNumber: 0,
        loading: 0,
        current: 0,
        showShareDialog:0,
        userInfo:{},
        autoplay:true,
        addCartProductId: -1,
        addCartNumber: -1
    },
    onPageScroll: function (e) {
        let scrollTop = e.scrollTop;
        let that = this;
        if (scrollTop >= 2000) {
            that.setData({
                showContact: 0
            })
        } else {
            that.setData({
                showContact: 1
            })
        }
    },
    openCartPage: function() {
        wx.switchTab({
            url: '/pages/cart/cart',
        });
    },
    goIndexPage: function() {
        wx.switchTab({
            url: '/pages/index/index',
        });
    },
    switchAttrPop: function() {
        if (this.data.openAttr == false) {
            this.setData({
                openAttr: !this.data.openAttr
            });
        }
    },
    closeAttr: function() {
        this.setData({
            openAttr: false,
            alone_text: '单独购买'
        });
    },
    goMarketing: function(e) {
        let that = this;
        that.setData({
            showDialog: !this.data.showDialog
        });
    },
    clickSkuValue: function(event) {
        // goods_specification中的id 要和product中的goods_specification_ids要一样
        let that = this;
        let specNameId = event.currentTarget.dataset.nameId;
        let specValueId = event.currentTarget.dataset.valueId;
        let index = event.currentTarget.dataset.index;
        //判断是否可以点击
        let _specificationList = this.data.specificationList;
        if (_specificationList.specification_id == specNameId) {
            for (let j = 0; j < _specificationList.valueList.length; j++) {
                if (_specificationList.valueList[j].id == specValueId) {
                    //如果已经选中，则反选
                    if (_specificationList.valueList[j].checked) {
                        _specificationList.valueList[j].checked = false;
                    } else {
                        _specificationList.valueList[j].checked = true;
                    }
                } else {
                    _specificationList.valueList[j].checked = false;
                }
            }
        }
        this.setData({
            'specificationList': _specificationList
        });
        //重新计算spec改变后的信息
        this.changeSpecInfo();

        //重新计算哪些值不可以点击
    },
    isCheckedAllSpec: function() {
        return !this.getCheckedSpecValue().some(function(v) {
            if (v.valueId == 0) {
                return true;
            }
        });
    },
    getCheckedSpecValue: function() {
        let checkedValues = [];
        let _specificationList = this.data.specificationList;
        let _checkedObj = {
            nameId: _specificationList.specification_id,
            valueId: 0,
            valueText: ''
        };
        for (let j = 0; j < _specificationList.valueList.length; j++) {
            if (_specificationList.valueList[j].checked) {
                _checkedObj.valueId = _specificationList.valueList[j].id;
                _checkedObj.valueText = _specificationList.valueList[j].value;
            }
        }
        checkedValues.push(_checkedObj);
        return checkedValues;
    },
    addCart: function(e) {
        // 判断是否登录，如果没有登录，则登录
        util.loginNow();
        var that = this;
        this.setData({
            openAttr: !that.data.openAttr,
            id: e.currentTarget.dataset.gid
        });
        let userInfo = wx.getStorageSync('userInfo');
        util.request(api.GoodsDetail, {
            id: e.currentTarget.dataset.gid
        }).then(function(res) {
            if (res.errno === 0) {
                let _specificationList = res.data.specificationList;
                // 如果仅仅存在一种货品，那么商品页面初始化时默认checked
                if (_specificationList.valueList.length == 1) {
                    _specificationList.valueList[0].checked = true
                    that.setData({
                        checkedSpecText: '已选择：' + _specificationList.valueList[0].value,
                        tmpSpecText: '已选择：' + _specificationList.valueList[0].value,
                    });
                } else {
                    that.setData({
                        checkedSpecText: '请选择规格和数量'
                    });
                }
                let galleryImages = [];
                for (const item of res.data.gallery) {
                    galleryImages.push(item.img_url);
                }

                that.setData({
                    goods: res.data.info,
                    goodsNumber: res.data.info.goods_number,
                    gallery: res.data.gallery,
                    specificationList: res.data.specificationList,
                    productList: res.data.productList,
                    checkedSpecPrice: res.data.info.retail_price,
                    galleryImages: galleryImages,
                    loading:1
                });
                setTimeout(() => {
                    console.log('---------------');
                    WxParse.wxParse('goodsDetail', 'html', res.data.info.goods_desc, that);
                }, 1000);
                wx.setStorageSync('goodsImage', res.data.info.https_pic_url);
            }
            else{
                util.showErrorToast(res.errmsg)
            }
        }).then(() => {
            let productLength = this.data.productList.length;
            if (userInfo == '') {
                return false;
            }
            if (this.data.openAttr == false && productLength != 1) {
                //打开规格选择窗口
                this.setData({
                    openAttr: !that.data.openAttr
                });
                this.setData({
                    alone_text: '加入购物车'
                })
            } else {
                //提示选择完整规格
                if (!this.isCheckedAllSpec()) {
                    wx.showToast({
                        image: '/images/icon/icon_error.png',
                        title: '请选择规格',
                    });
                    return false;
                }
                //根据选中的规格，判断是否有对应的sku信息
                let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey());
                if (!checkedProductArray || checkedProductArray.length <= 0) {
                    //找不到对应的product信息，提示没有库存
                    wx.showToast({
                        image: '/images/icon/icon_error.png',
                        title: '库存不足',
                    });
                    return false;
                }
                let checkedProduct = checkedProductArray[0];
                //验证库存
                if (checkedProduct.goods_number < this.data.number) {
                    //要买的数量比库存多
                    wx.showToast({
                        image: '/images/icon/icon_error.png',
                        title: '库存不足',
                    });
                    return false;
                }
            }
        });
    },

    subCart: function (e) {
        let id = e.currentTarget.dataset.gid
        let thisIndex = this.data.list.findIndex(n => n.id === id)
        let productId = this.data.list[thisIndex].productId
        let number = this.data.list[thisIndex].cartNumber
        let cartId = this.data.list[thisIndex].cartId

        if(number && number === 1) {
            util.request(api.CartDelete, {
                productIds: productId
            }, 'POST').then((res) => {
                if (res.errno === 0) {
                    wx.showToast({
                        title: '此商品已清零',
                    })
                    this.setData({
                        cartGoodsCount: res.data.cartTotal.goodsCount
                    })
                }
            }).then(() => {
                this.getGoodsCartNumber()
                let cartCount = this.data.cartGoodsCount
                if(cartCount !== 0) {
                    wx.setTabBarBadge({
                        index: 2,
                        text: cartCount.toString()
                    })
                }else {
                    wx.removeTabBarBadge({
                        index: 2,
                    })
                }

            });
        } else if(number && number > 1) {
            util.request(api.CartUpdate, {
                productId: productId,
                number:  number - 1,
                id: cartId
            }, 'POST').then((res) => {
                this.setData({
                    cartGoodsCount: res.data.cartTotal.goodsCount
                });
            }).then(() => {
                this.getGoodsCartNumber()
                wx.setTabBarBadge({
                    index: 2,
                    text: this.data.cartGoodsCount.toString()
                })
            })
        }
    },

    fastToCart: function() {
        // 判断是否登录，如果没有登录，则登录
        util.loginNow();
        let userInfo = wx.getStorageSync('userInfo');
        if (userInfo == '') {
            return false;
        }
        var that = this;
        if (this.data.openAttr === false) {
            //打开规格选择窗口
            this.setData({
                openAttr: !this.data.openAttr
            });
            that.setData({
                alone_text: '加入购物车'
            })
        } else {
            //提示选择完整规格
            if (!this.isCheckedAllSpec()) {
                wx.showToast({
                    image: '/images/icon/icon_error.png',
                    title: '请选择规格',
                });
                return false;
            }
            //根据选中的规格，判断是否有对应的sku信息
            let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey());
            if (!checkedProductArray || checkedProductArray.length <= 0) {
                //找不到对应的product信息，提示没有库存
                wx.showToast({
                    image: '/images/icon/icon_error.png',
                    title: '库存不足',
                });
                return false;
            }
            let checkedProduct = checkedProductArray[0];
            //验证库存
            if (checkedProduct.goods_number < this.data.number) {
                //要买的数量比库存多
                wx.showToast({
                    image: '/images/icon/icon_error.png',
                    title: '库存不足',
                });
                return false;
            }
            //添加到购物车
            wx.showLoading({
                title: '',
                mask:true
              })
            util.request(api.CartAdd, {
                    addType: 1, // 0：正常加入购物车，1:立即购买，2:再来一单
                    goodsId: this.data.id,
                    number: this.data.number,
                    productId: checkedProduct.id,
                }, "POST")
                .then(function(res) {
                    let _res = res;
                    wx.hideLoading()
                    if (_res.errno == 0) {
                        let id = that.data.id;
                        wx.navigateTo({
                            url: '/pages/order-check/index?addtype=1'
                        });
                    } else {
                        wx.showToast({
                            image: '/images/icon/icon_error.png',
                            title: _res.errmsg,
                        });
                    }
                });
        }
    },
    addToCart: function() {
        // 判断是否登录，如果没有登录，则登录
        util.loginNow();
        var that = this;
        let userInfo = wx.getStorageSync('userInfo');
        let productLength = this.data.productList.length;

        let thisIndex = this.data.list.findIndex(n => n.id == this.data.id)
        let productId = this.data.list[thisIndex].productId
        let number = this.data.list[thisIndex].cartNumber
        let cartId = this.data.list[thisIndex].cartId

        if (userInfo == '') {
            return false;
        }
        if (this.data.openAttr == false && productLength != 1) {
            //打开规格选择窗口
            this.setData({
                openAttr: !that.data.openAttr
            });
            this.setData({
                alone_text: '加入购物车'
            })
        } else {
            //提示选择完整规格
            if (!this.isCheckedAllSpec()) {
                wx.showToast({
                    image: '/images/icon/icon_error.png',
                    title: '请选择规格',
                });
                return false;
            }
            //根据选中的规格，判断是否有对应的sku信息
            let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey());
            if (!checkedProductArray || checkedProductArray.length <= 0) {
                //找不到对应的product信息，提示没有库存
                wx.showToast({
                    image: '/images/icon/icon_error.png',
                    title: '库存不足',
                });
                return false;
            }
            let checkedProduct = checkedProductArray[0];
            //验证库存
            if (checkedProduct.goods_number < this.data.number) {
                //要买的数量比库存多
                wx.showToast({
                    image: '/images/icon/icon_error.png',
                    title: '库存不足',
                });
                return false;
            }
            wx.showLoading({
                title: '',
                mask: true
            })
            if (!number) {
                util.request(api.CartAdd, {
                    addType: 0,
                    goodsId: this.data.id,
                    number: this.data.number,
                    productId: checkedProduct.id
                }, "POST")
                    .then(function (res) {
                        let _res = res;
                        if (_res.errno == 0) {
                            wx.showToast({
                                title: '添加成功',
                            });
                            if (productLength != 1 || that.data.openAttr == true) {
                                that.setData({
                                    openAttr: !that.data.openAttr,
                                    cartGoodsCount: _res.data.cartTotal.goodsCount
                                });
                            } else {
                                that.setData({
                                    cartGoodsCount: _res.data.cartTotal.goodsCount
                                });
                            }
                        } else {
                            wx.showToast({
                                image: '/images/icon/icon_error.png',
                                title: _res.errmsg,
                            });
                        }
                        wx.hideLoading()
                    }).then(() => {
                    this.getGoodsCartNumber()
                    this.setData({
                        number: 1,
                    })
                    wx.setTabBarBadge({
                        index: 2,
                        text: this.data.cartGoodsCount.toString()
                    })
                });
            } else if (number && number > 0) {
                util.request(api.CartUpdate, {
                    productId: productId,
                    number: this.data.number + number,
                    id: cartId
                }, 'POST').then((res) => {
                    if (res.errno == 0) {
                        wx.showToast({
                            title: '添加成功',
                        });
                        if (productLength != 1 || that.data.openAttr == true) {
                            that.setData({
                                openAttr: !that.data.openAttr,
                                cartGoodsCount: res.data.cartTotal.goodsCount
                            });
                        } else {
                            that.setData({
                                cartGoodsCount: res.data.cartTotal.goodsCount
                            });
                        }
                    } else {
                        wx.showToast({
                            image: '/images/icon/icon_error.png',
                            title: res.errmsg,
                        });
                    }
                    wx.hideLoading()

                }).then(() => {
                    this.getGoodsCartNumber()
                    this.setData({
                        number: 1,
                    })
                    wx.setTabBarBadge({
                        index: 2,
                        text: this.data.cartGoodsCount.toString()
                    })
                });
            }
        }
    },
    changeSpecInfo: function() {
        let checkedNameValue = this.getCheckedSpecValue();
        this.setData({
            disabled: '',
            number: 1
        });
        //设置选择的信息
        let checkedValue = checkedNameValue.filter(function(v) {
            if (v.valueId != 0) {
                return true;
            } else {
                return false;
            }
        }).map(function(v) {
            return v.valueText;
        });
        if (checkedValue.length > 0) {
            this.setData({
                tmpSpecText: '已选择：' + checkedValue.join('　'),
                priceChecked: true

            });
        } else {
            this.setData({
                tmpSpecText: '请选择规格和数量',
                priceChecked: false
            });
        }

        if (this.isCheckedAllSpec()) {
            this.setData({
                checkedSpecText: this.data.tmpSpecText
            });

            // 点击规格的按钮后
            // 验证库存
            let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey());
            if (!checkedProductArray || checkedProductArray.length <= 0) {
                this.setData({
                    soldout: true
                });
                // console.error('规格所对应货品不存在');
                wx.showToast({
                    image: '/images/icon/icon_error.png',
                    title: '规格所对应货品不存在',
                });
                return;
            }
            let checkedProduct = checkedProductArray[0];
            if (checkedProduct.goods_number < this.data.number) {
                //找不到对应的product信息，提示没有库存
                this.setData({
                    checkedSpecPrice: checkedProduct.retail_price,
                    goodsNumber: checkedProduct.goods_number,
                    soldout: true
                });
                wx.showToast({
                    image: '/images/icon/icon_error.png',
                    title: '库存不足',
                });
                return false;
            }
            if (checkedProduct.goods_number > 0) {
                this.setData({
                    checkedSpecPrice: checkedProduct.retail_price,
                    goodsNumber: checkedProduct.goods_number,
                    soldout: false
                });

                var checkedSpecPrice = checkedProduct.retail_price;

            } else {
                this.setData({
                    checkedSpecPrice: this.data.goods.retail_price,
                    soldout: true
                });
            }
        } else {
            this.setData({
                checkedSpecText: '请选择规格和数量',
                checkedSpecPrice: this.data.goods.retail_price,
                soldout: false
            });
        }
    },
    getCheckedProductItem: function(key) {
        return this.data.productList.filter(function(v) {
            if (v.goods_specification_ids == key) {
                return true;
            } else {
                return false;
            }
        });
    },
    cutNumber: function() {
        this.setData({
            number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
        });
        this.setData({
            disabled: ''
        });
    },
    addNumber: function() {
        this.setData({
            number: Number(this.data.number) + 1
        });
        let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey());
        let checkedProduct = checkedProductArray;
        var check_number = this.data.number + 1;
        if (checkedProduct.goods_number < check_number) {
            this.setData({
                disabled: true
            });
        }
    },
    inputNumber(event) {
        let number = event.detail.value;
        this.setData({
            number: number
        });
    },
    getCheckedSpecKey: function() {
        let checkedValue = this.getCheckedSpecValue().map(function(v) {
            return v.valueId;
        });
        return checkedValue.join('_');
    },
    onReachBottom:function(){
        this.onBottom()
    },
    onHide:function(){
        this.setData({
            autoplay:false
        })
    },
    goSearch: function () {
        wx.navigateTo({
            url: '/pages/search/search',
        })
    },
    goCategory: function (e) {
        let id = e.currentTarget.dataset.cateid;
        wx.setStorageSync('categoryId', id);
        wx.switchTab({
            url: '/pages/category/index',
        })
    },
    handleTap: function (event) {
        //阻止冒泡
    },
    onShareAppMessage: function () {
        let info = wx.getStorageSync('userInfo');
        return {
            title: '超市',
            desc: '超市',
            path: '/pages/index/index?id=' + info.id
        }
    },
    toDetailsTap: function () {
        wx.navigateTo({
            url: '/pages/goods-details/index',
        });
    },
    bindscroll:function(event){
        console.log(event.detail);
    },

    getCurrentList: function(id) {
        let that = this;
        util.request(api.GetHomeList, {
            size: that.data.size,
            page: that.data.allPage,
            id: id
        }, 'POST').then(function(res) {
            if (res.errno === 0) {
                let count = res.data.count;
                that.setData({
                    allCount: count,
                    allPage: res.data.currentPage,
                    list: that.data.list.concat(res.data.data),
                    showNoMore: 1,
                    loading: 1,
                });
                if (count == 0) {
                    that.setData({
                        hasInfo: 0,
                        showNoMore: 0
                    });
                }
            }
        }).then(() => {
            this.getGoodsCartNumber()
        })
    },
    getIndexData: function () {
        let that = this;
        util.request(api.IndexUrl).then(function (res) {
            if (res.errno === 0) {
                that.setData({
                    floorGoods: res.data.categoryList,
                    banner: res.data.banner,
                    channel: res.data.channel,
                    notice: res.data.notice,
                    loading: 1,
                });
                let cartGoodsCount = '';
                if (res.data.cartCount == 0) {
                    wx.removeTabBarBadge({
                        index: 2,
                    })
                } else {
                    cartGoodsCount = res.data.cartCount + '';
                    wx.setTabBarBadge({
                        index: 2,
                        text: cartGoodsCount
                    })
                }
            }
        });
    },
    onLoad: function (options) {
        this.getCurrentList(0);
        this.getChannelShowInfo();
        console.log(options);
    },
    onShow: function () {
        this.getIndexData();
        var that = this;
        let userInfo = wx.getStorageSync('userInfo');
        if (userInfo != '') {
            that.setData({
                userInfo: userInfo,
            });
        };
        let info = wx.getSystemInfoSync();
        let sysHeight = info.windowHeight - 100;
        this.setData({
            sysHeight: sysHeight,
            autoplay:true
        });
        wx.removeStorageSync('categoryId');
        this.getGoodsCartNumber()
    },
    getChannelShowInfo: function (e) {
        let that = this;
        util.request(api.ShowSettings).then(function (res) {
            if (res.errno === 0) {
                let show_channel = res.data.channel;
                let show_banner = res.data.banner;
                let show_notice = res.data.notice;
                let index_banner_img = res.data.index_banner_img;
                that.setData({
                    show_channel: show_channel,
                    show_banner: show_banner,
                    show_notice: show_notice,
                    index_banner_img: index_banner_img
                });
            }
        });
    },
    onBottom: function() {
        let that = this;
        if (that.data.allCount / that.data.size < that.data.allPage) {
            that.setData({
                showNoMore: 0
            });
            return false;
        }
        that.setData({
            allPage: that.data.allPage + 1
        });
        let nowId = that.data.nowId;
        if (nowId == 0 || nowId == undefined) {
            that.getCurrentList(0);
        } else {
            that.getCurrentList(nowId);
        }
    },
    onPullDownRefresh: function () {
        wx.showNavigationBarLoading()
        this.getIndexData();
        this.getChannelShowInfo();
        this.setData({
            list: [],
            allPage: 1,
            allCount: 0,
            size: 4,
        })
        this.data.specificationList = []
        this.getCurrentList(0);
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
    },

    getGoodsCartNumber() {
        let that = this;
        util.request(api.CartList).then((res) => {
            if (res.errno === 0) {
                let list = this.data.list
                let newList = []
                list.forEach((item) => {
                    for(let k of res.data.cartList) {
                        if(k.goods_id === item.id) {
                            item.cartNumber = k.number
                            item.productId = k.product_id
                            item.cartId = k.id
                            newList.push(item)
                            return
                        }
                    }
                    delete item.cartNumber
                    delete item.productId
                    delete item.cartId
                    newList.push(item)
                })
                that.setData({
                    list: newList
                })
                if(res.data.cartTotal.goodsCount) {
                    wx.setTabBarBadge({
                        index: 2,
                        text: res.data.cartTotal.goodsCount.toString()
                    })
                }
            }
        });
    },
})
